<?php

namespace app\api\controller\meet;

use app\common\controller\Api;
use app\common\model\Area;


class Join extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * @var \app\common\model\meet\Join
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();

        $this->model = new \app\common\model\meet\Join();
    }

    public function submit()
    {
        $post = $this->request->post();

        if (empty($post)) {
            $this->error(__('Invalid parameters'));
        }

        //是否已申请
        $join_id = $this->model->where('user_id', '=', $this->auth->id)->value('id');
        if (!empty($join_id)) {
            $this->error(__('Applied, please do not resubmit'));
        }

        $validate = new \app\api\validate\meet\Join();

        $check = $validate->check($post);

        if (!$check) {
            $this->error(__($validate->getError()));
        }

        $area_column = Area::where('id', 'in', [$post['province_id'], $post['city_id'], $post['area_id']])->column('name');

        if (empty($area_column)) {
            $this->error(__('Provincial and urban area acquisition failed'));
        }

        $data = [
            'name' => $post['name'],
            'mobile' => $post['mobile'],
            'province_id' => $post['province_id'],
            'city_id' => $post['city_id'],
            'area_id' => $post['area_id'],
            'full_area' => implode(' ', $area_column),
            'remark' => $post['remark'] ?? ''
        ];

        if ($this->auth->isLogin()) {
            $data['user_id'] = $this->auth->id;
        }

        $result = $this->model->save($data);

        if (!$result) {
            $this->error(__('Operation failed'));
        }

        $this->success(__('Operation completed'));
    }
}
